package com.xy.smartsms.db.carrierparam;

import android.content.Context;
import android.util.LruCache;

import com.xy.smartsms.db.carrierparam.entity.BlackListDb;
import com.xy.smartsms.db.carrierparam.entity.BlackListItem;

/**
 * Created by admin on 2017/2/24.
 */

public class BlackListManager {
    private LruCache<String, BlackListItem> mItemCache = new LruCache<String, BlackListItem>(100);
    private final String TAG = "BlackListManager";
    private Context mContext;

    private synchronized BlackListItem getItem(String phone) {
        BlackListItem item = mItemCache.get(phone);
        return item;
    }

    public boolean isLoadSuccess(String phone) {
        BlackListItem item = mItemCache.get(phone);
        if (item != null) {
            return true;
        }
        return false;
    }

    public BlackListItem preLoadData(final String phone) {
        BlackListItem item = mItemCache.get(phone);
        if (item == null) {
            item = BlackListDb.getInstance().queryByPhone(phone);
            mItemCache.put(phone, item);
        }
        return item;
    }


    public void updateOrInsert(BlackListItem item) {
        if (item == null)
            return;
        BlackListDb.getInstance().updateOrInsert(item);
        mItemCache.remove(item.getPhone());
    }

    public void delete(BlackListItem item) {
        BlackListDb.getInstance().delete(item);
        mItemCache.remove(item.getPhone());
    }

    public boolean checkSwitch(String phone, int funcType) {
        BlackListItem item = getItem(phone);
        if (item == null)
            return false;
        return (item.getFuncBitwise() & funcType) != 0;
    }

    public boolean checkDisplay(String phone, int funcType) {
        BlackListItem item = getItem(phone);
        if (item == null)
            return false;
        return (item.getDisplayBitwise() & funcType) != 0;
    }

    public void initDataToDb() {
    }

    public void clearCache() {
        if (mItemCache != null)
            mItemCache.evictAll();
    }

    private BlackListManager(Context context) {
        mContext = context;
        BlackListDb.getInstance(mContext);
    }

    private static BlackListManager sBlackListManager = null;

    public static BlackListManager getInstance() {
        return sBlackListManager;
    }

    public static BlackListManager getInstance(Context context) {
        synchronized (BlackListManager.class) {
            if (sBlackListManager == null) {
                sBlackListManager = new BlackListManager(context);
            }
        }

        return sBlackListManager;
    }
}
